/*
 * @Description: ------------ fileDescription -----------
 * @Author: snows_l snows_l@163.com
 * @Date: 2024-04-07 14:41:16
 * @LastEditors: snows_l snows_l@163.com
 * @LastEditTime: 2024-12-18 16:35:13
 * @FilePath: \Backstage\Server\src\router\dict.js
 */
const express = require('express');
const { verifyToken } = require('../utils/handleToken');
const { handleError } = require('../utils/common.js');
// 数据库操作
const db = require('../utils/connDB');

// 工具函数
const router = express.Router();
// list转tree的函数
const { tranListToTree } = require('../utils/common');

// 获取字典
router.get('/list', (req, res) => {
  let token = req.cookies['bs-cookie'];
  try {
    const user = verifyToken(token);
    if (!user) throw new Error('JsonWebTokenError:token验证失败');
    const reqParams = req.query;
    let params = {
      name: reqParams.name || '',
      dictType: reqParams.dictType || '',
      isAll: reqParams.isAll || false
    };

    // admin和visitor角色可以查看所有字典
    if (user.role_key === 'visitor' || user.role_key === 'admin') {
      let sql = 'select* from sys_dict order by sort ASC;';
      if (params.name) {
        sql = `select * from sys_dict where label like '%${params.name}%' or dictType like '%${params.name}%' order by sort ASC;`;
      }
      db.queryAsync(sql).then(res1 => {
        if (!res1.results.length)
          return res.send({
            code: 200,
            data: [],
            msg: 'success'
          });
        let userTypeArr = [];
        res1.results.forEach(item => {
          userTypeArr.push("'" + item.dictType + "'");
        });
        let userTypeArrStr = userTypeArr.join(',');
        let resultSql = `select * from sys_dict where dictType in (${userTypeArrStr}) order by sort ASC;`;
        db.queryAsync(resultSql)
          .then(res2 => {
            let source = res2.results;

            if (user.role_key === 'visitor') {
              source.forEach((item, index) => {
                if (item.dictType == 'favors_time') {
                  if (item.pid == 0) {
                    item.label = '来往时间点';
                  } else {
                    item.label = `时间节点${item.value}`;
                    item.remark = `小秘密${item.value}，不能偷看的`;
                  }
                }
                if (item.dictType == 'wages_source') {
                  if (!item.pid == 0) {
                    item.label = `企业${item.value}`;
                    item.remark = `小秘密${item.value}，不能偷看的`;
                  }
                }
              });
            }
            res.send({
              code: 200,
              data: tranListToTree(source, 'id', 'pid'),
              msg: 'success'
            });
          })
          .catch(err => {
            res.send({
              code: 500,
              data: null,
              msg: err
            });
          });
      });
    } else {
      let sql = `select * from sys_dict where dictType = ? and role_key = ? order by sort ASC;`;
      const params = ['favors_time', user.role_key];
      db.queryAsync(sql, params)
        .then(res1 => {
          let source = res1.results;
          res.send({
            code: 200,
            data: tranListToTree(source, 'id', 'pid'),
            msg: 'success'
          });
        })
        .catch(err => {
          handleError(res, err);
        });
    }
  } catch (error) {
    handleError(res, err);
  }
});

// 获取指定字典详情
router.get('/detail', (req, res) => {
  // 移动端不需要登录
  let token = req.cookies['bs-cookie'];
  const { dictType } = req.query;
  try {
    if (!dictType) throw new Error('dictType不能为空');
    let sql = `select * from sys_dict where dictType='${dictType}' and pid <> 0 order by sort ASC;`;
    if (dictType == 'favors_time') {
      const user = verifyToken(token);
      if (!user) throw new Error('JsonWebTokenError:token验证失败');
      sql = `select * from sys_dict where dictType='${dictType}' and role_key = '${user.role_key}' and pid <> 0 order by sort ASC;`;
      if (user.role_key == 'admin') {
        sql = `select * from sys_dict where dictType='${dictType}' and pid <> 0 order by sort ASC;`;
      }
    }
    db.queryAsync(sql)
      .then(result => {
        res.send({
          code: 200,
          data: result.results,
          msg: 'success'
        });
      })
      .catch(err => {
        handleError(res, err);
      });
  } catch (error) {
    handleError(res, error);
  }
});

// 删除字典
router.delete('/delete', (req, res) => {
  let token = req.cookies['bs-cookie'];
  try {
    const user = verifyToken(token);
    if (!user) throw new Error('JsonWebTokenError:token验证失败');
    if (user.role_key === 'visitor') throw new Error('visitor权限不足');
    const reqParams = req.body;
    let params = {
      id: reqParams.id
    };

    let selectSql = `select * from sys_dict where id=${params.id}`;
    let deleteSql = `delete from sys_dict where id=${params.id}`;
    db.queryAsync(selectSql)
      .then(res1 => {
        if (!res1.results.length) {
          return res.send({
            code: 200,
            data: 0,
            msg: '字典不存在'
          });
        }
        // 如果删除顶级字典，则删除其下级字典
        if (res1.results[0].pid == 0) {
          let selectDictSql = `select * from sys_dict where dictType='${res1.results[0].dictType}';`;
          if (res1.results[0].dictType == 'favors_time') {
            selectDictSql = `select * from sys_dict where dictType='${res1.results[0].dictType}' and role_key = '${res1.results[0].role_key}';`;
          }
          db.queryAsync(selectDictSql).then(res2 => {
            let ids = res2.results.map(item => item.id).join(',');
            deleteSql = `delete from sys_dict where id in (${ids})`;
            db.queryAsync(deleteSql)
              .then(res2 => {
                res.send({
                  code: 200,
                  data: res2.affectedRows,
                  msg: '删除成功'
                });
              })
              .catch(err => {
                handleError(res, err);
              });
          });
        } else {
          db.queryAsync(deleteSql)
            .then(res2 => {
              res.send({
                code: 200,
                data: res2.affectedRows,
                msg: '删除成功'
              });
            })
            .catch(err => {
              handleError(res, err);
            });
        }
      })
      .catch(err => {
        handleError(res, err);
      });
  } catch (error) {
    handleError(res, error);
  }
});

// 新增字典
router.post('/add', (req, res) => {
  let token = req.cookies['bs-cookie'];
  try {
    const user = verifyToken(token);
    if (!user) throw new Error('JsonWebTokenError:token验证失败');
    if (user.role_key === 'visitor') throw new Error('visitor权限不足');
    const reqParams = req.body;
    let params = {
      label: reqParams.label,
      value: reqParams.value,
      dictType: reqParams.dictType,
      pid: reqParams.pid || 0,
      sort: reqParams.sort || 0,
      remark: reqParams.remark || '',
      role_key: reqParams.role_key || '',
      role_str: reqParams.role_str || ''
    };
    let sql = `insert into sys_dict (label, value, dictType, pid, sort, remark,  createTime, role_key, role_str) values (?, ?, ?, ?, ?, ?, ?, ?, ?);`;

    db.queryAsync(sql, [
      params.label,
      params.value,
      params.dictType,
      params.pid,
      params.sort,
      params.remark,
      new Date(),
      params.role_key || user.role_key,
      params.role_key ? params.role_str : user.role_str
    ])
      .then(res1 => {
        res.send({
          code: 200,
          data: res1.insertId,
          msg: '新增成功'
        });
      })
      .catch(err => {
        handleError(res, err);
      });
  } catch (error) {
    handleError(res, err);
  }
});

// 修改字典
router.post('/edit', (req, res) => {
  let token = req.cookies['bs-cookie'];
  try {
    const user = verifyToken(token);
    if (!user) throw new Error('JsonWebTokenError:token验证失败');
    if (user.role_key === 'visitor') throw new Error('visitor权限不足');
    const reqParams = req.body;
    let params = {
      id: reqParams.id,
      label: reqParams.label,
      value: reqParams.value == 'undefined' || reqParams.value == 'null' ? '' : reqParams.value || '',
      dictType: reqParams.dictType,
      pid: reqParams.pid || 0,
      sort: reqParams.sort || 0,
      remark: reqParams.remark || '',
      role_key: reqParams.role_key || '',
      role_str: reqParams.role_str || ''
    };
    let sql = `update sys_dict set label=?, value=?, dictType=?, pid=?, sort=?, remark=?, role_key=?, role_str=?, updateTime=? where id=?;`;
    const paramsArr = [
      params.label,
      params.value,
      params.dictType,
      params.pid,
      params.sort,
      params.remark,
      params.role_key || user.role_key,
      params.role_key ? params.role_str : user.role_str,
      new Date(),
      params.id
    ];
    db.queryAsync(sql, paramsArr)
      .then(res1 => {
        res.send({
          code: 200,
          data: res1.affectedRows,
          msg: '修改成功'
        });
      })
      .catch(err => {
        handleError(res, err);
      });
  } catch (error) {
    handleError(res, err);
  }
});

module.exports = router;
